package com.onlyxiahui.common.utils.base.io;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

public class PropertiesUtil {

	/**
	 * 
	 * Description ClassPath获取<br>
	 * Date 2020-11-10 14:34:06<br>
	 * 
	 * @param classPath
	 * @return ResourceBundle
	 * @since 1.0.0
	 */
	public static ResourceBundle getResourceBundleByClassPath(String classPath) {
		ResourceBundle rb = null;
		InputStream in = null;
		try {
			in = PropertiesUtil.class.getResourceAsStream(classPath);
			rb = new PropertyResourceBundle(in);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return rb;
	}

	/**
	 * 
	 * Description 文件路径（FilePath）获取<br>
	 * Date 2020-11-10 14:36:56<br>
	 * 
	 * @param path
	 * @return ResourceBundle
	 * @since 1.0.0
	 */
	public static ResourceBundle getResourceBundleByFilePath(String filePath) {
		ResourceBundle rb = null;
		InputStream in = null;
		try {
			if (FileUtil.isFileExists(filePath)) {
				in = new BufferedInputStream(new FileInputStream(filePath));
				rb = new PropertyResourceBundle(in);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return rb;
	}

	/**
	 * Description 根据classpath路径读取配置文件属性<br>
	 * <p>
	 * String address =
	 * PropertiesUtil.getProperty("config/setting/config.properties","remote.server.address");
	 * <p>
	 * 
	 * @param classPath ：classpath的文件路径："/com/common/config.properties"
	 * @param path
	 * @param name
	 * @return
	 * @since 1.0.0
	 */
	public static String getPropertyByClassPath(String classPath, String name) {
		ResourceBundle rb = getResourceBundleByClassPath(classPath);
		if (null == rb) {
			return null;
		}
		if (rb.containsKey(name)) {
			return rb.getString(name);
		} else {
			return null;
		}
	}

	/**
	 * Description 根据路径读取配置文件属性<br>
	 * path根据文件路径如:<br>
	 * 绝对路径"E:/resources/config.properties"<br>
	 * 相对路径："resources/config.properties"<br>
	 * <br>
	 * Date 2019-03-30 17:31:48<br>
	 * 
	 * @param filePath
	 * @param name
	 * @return String
	 * @since 1.0.0
	 */
	public static String getPropertyByFilePath(String filePath, String name) {
		ResourceBundle rb = getResourceBundleByFilePath(filePath);
		if (null == rb) {
			return null;
		}
		if (rb.containsKey(name)) {
			return rb.getString(name);
		} else {
			return null;
		}
	}
}
